﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Platform;
using NewRetail.Application.Components.Platform.Entity;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Linq.Dynamic.Core;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("pos-integral-usage-rule")]
    public class PosIntegralUsageRuleController : BaseController<PosIntegralUsageRule, PagingRequestDto>
    {
        private readonly IPosIntegralUsageRuleService _posIntegralUsageRuleService;

        public PosIntegralUsageRuleController(IPosIntegralUsageRuleService posIntegralUsageRuleService)
        {
            this._posIntegralUsageRuleService = posIntegralUsageRuleService;
        }
        public override async Task<ResponseEntity<PagedResultDto<PosIntegralUsageRule>>> QueryPaging([FromBody] PagingRequestDto dto)
        {
            var data = await base.QueryPaging(dto);
            if (data.Data?.Items?.Any() ?? false)
            {
                data.Data.Items = await this._posIntegralUsageRuleService.AttachWarehouse(data.Data.Items.ToArray());
            }
            return data;
        }

        [HttpPost("save-multiple")]
        public async Task<ResponseEntity<PosIntegralUsageRule[]>> SaveMultiple([FromBody] ReceiptNoItemsDto<PosIntegralUsageRule> data)
        {
            var res = await this.Repo.SaveReceiptItems(this.HttpContext.RequestServices, data, "PIUR");
            return new ResponseEntity<PosIntegralUsageRule[]>().SetData(res.Items);
        }

        [HttpPost("query-by-receipt-no")]
        public async Task<ResponseEntity<PosIntegralUsageRule[]>> QueryByReceiptNo([FromBody] ReceiptNoDto dto)
        {
            dto.Should().NotBeNull();
            dto.receiptNo.Should().NotBeNullOrEmpty();
            var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
            var data = await query.Where(x => x.receiptNo == dto.receiptNo).ToArrayAsync();

            return new ResponseEntity<PosIntegralUsageRule[]>().SetData(data);
        }
        [HttpPost("get-posintegral-usage-rule")]
        public async Task<ResponseEntity<PosIntegralUsageRule[]>> GetPosIntegralUsageRules([FromBody] GetPosIntegralUsageRuleDto dto)
        {
            dto.Should().NotBeNull();
            dto.Page ??= 1;
            (dto.Page >= 1).Should().BeTrue();

            var db = await this.Repo.GetDbContextAsync();

            var query = db.Set<PosIntegralUsageRule>().IgnoreQueryFilters().AsNoTracking();

            if (dto.UpdateTime != null)
            {
                query = query.Where(x => x.updateTime >= dto.UpdateTime.Value);
            }

            query = query.OrderBy(x => x.updateTime).Page(dto.Page.Value, pageSize: 100);

            var data = await query.ToArrayAsync();

            return new ResponseEntity<PosIntegralUsageRule[]>().SetData(data);
        }

        /// <summary>
        /// 根据会员、兑换金额计算出可使用积分（积分抵现）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("get-posintegral-usage-amount")]
        public async Task<ResponseEntity<MemberIntegralUsageAmountResponseDto>> GetPosMemberIntegralUsageAmount([FromBody] MemberIntegralUsageAmountDto dto)
        {
            dto.Should().NotBeNull();
            var ret = new ResponseEntity<MemberIntegralUsageAmountResponseDto>();
            var result = await this._posIntegralUsageRuleService.PosMemberIntegralUsageAmount(dto);

            if (!string.IsNullOrWhiteSpace(result.Item3))
                ret.SetError("失败！" + result.Item2);
            else
                ret.SetData(new MemberIntegralUsageAmountResponseDto() { availableRedemptionAmount = result.Item1, useIntegral = result.Item2 });

            return ret;
        }
    }
}
